from sqlalchemy.orm import Session
from core.database import SessionLocal
from core.logger import log
from db.mysql.devices import Devices


class DevicesDao:
    def __init__(self,db: Session = None):
        self.db = db or SessionLocal()

    def create_devices(self,devices_data: dict,auto_commit=True):
        """
        创建设备
        :param devices_data:
        :param auto_commit:
        :return:
        """
        try:
            devices = Devices(**devices_data)
            self.db.add(devices)
            if auto_commit:
                self.db.commit()
                self.db.refresh(devices)
            else:
                self.db.flush()
            log.info("设备创建成功", devices)
            return devices
        except Exception as e:
            log.error("设备创建失败", e)
            if auto_commit:
                self.db.rollback()
            else:
                raise
    def update_devices_by_device_id(self,devices_id: str, devices_data: dict, auto_commit=True):
        """
        更新设备
        :param devices_id:
        :param devices_data:
        :param auto_commit:
        :return:
        """
        try:
            device = self.db.query(Devices).filter(Devices.device_id == devices_id).first()
            if device:
                for key, value in devices_data.items():
                    setattr(device, key, value)
                if auto_commit:
                    self.db.commit()
                    self.db.refresh(device)
                else:
                    self.db.flush()
                log.info("设备更新成功", device)
                return device
            raise Exception("设备不存在")
        except Exception as e:
            log.error(f"更新设备失败: {str(e)}")
            if auto_commit:
                self.db.rollback()
            else:
                raise  # 重新抛出异常让外层处理
    def update_device_template_id(self,device:Devices,template_id:str,auto_commit=True):
        """
        更新设备模板ID
        :param device:
        :param template_id
        :return:
        """
        try:
            # 更新设备的模板ID字段
            device.template_id = template_id
            if auto_commit:
                self.db.commit()
                self.db.refresh(device)
            else:
                self.db.flush()
            log.info("设备模板ID更新成功", device)
            return device
        except Exception as e:
            if auto_commit:
                self.db.rollback()
            else:
                raise

    def delete_devices(self,device_id: str, auto_commit=True):
        """
        删除模板
        :param device_id:
        :return:
        """
        try:
            device = self.db.query(Devices).filter(Devices.device_id == device_id).first()
            if device:
                self.db.delete(device)
                if auto_commit:
                    self.db.commit()
                else:
                    self.db.flush()
                log.info("设备删除成功", device)
                return device
            raise Exception("设备不存在")
        except Exception as e:
            log.error(f"删除设备失败: {str(e)}")
            if auto_commit:
                self.db.rollback()
            else:
                raise
    def get_device_by_device_id(self, device_id: str):
        """
        获取设备通过device_id获取
        :param device_id:
        :return:
        """
        try:
            devices = self.db.query(Devices).filter(Devices.device_id == device_id).first()
            if devices:
                log.info("获取设备成功", devices)
                return devices
            raise Exception("设备不存在")
        except Exception as e:
            log.error(f"获取设备失败: {str(e)}")
    def get_device_by_phone(self, device_phone: str):
        """
        获取设备通过device_phone获取
        :param device_phone:
        :return:
        """
        try:
            devices = self.db.query(Devices).filter(Devices.device_phone == device_phone).first()
            if devices:
                log.info("获取设备成功", devices)
                return devices
            raise Exception("设备不存在")
        except Exception as e:
            log.error(f"获取设备失败: {str(e)}")
    def get_all_devices_by_user(self,user_id: str)-> list:
        """
        获取所有模板
        :return:
        """
        try:
            devices = self.db.query(Devices).filter(Devices.user_id == user_id).all()
            log.info("获取所有模板成功", devices)
            return devices
        except Exception as e:
            log.error(f"获取所有模板失败: {str(e)}")


